<template>
	<view class="dutys_box">
		<Tips />
		<ClockNoN :nowDormitoryWeekTypeStr="nowDormitoryWeekType === WeekType.SIGLE ? '单周' : '双周'" v-if="clocks" :clocks="clocks"/>
		<AdBanner width="100%"/>
		<view class="choose">
			<uni-segmented-control 
				:current="formData.weekType" 
				:values="items" 
				style-type="button"
				:active-color="primary_hot_color" 
				@clickItem="onChooseFun" />
		</view>
		<MySteps :color="stepColor(item.duty[0])" :active="item.duty[0].week === nowWeek" v-for="(item,index) in dutys" :key="item.id">
			<view class="duty_card">
				<uni-badge :customStyle="{background: primary_hot_color}"
					:text="item.duty[0].week === nowWeek && !dormitoryDutyIsPause &&nowDormitoryWeekType===formData.weekType  ? '今天值日' : ''" absolute="rightTop" :offset="[25, 15]"
					size="small">
					<DutyCard @isDeleteDutyModelEmit="isDeleteDutyModelFun" @openEditDutyModalEmt="openEditDutyModalFun"
						:dutyData="item.duty"/>
				</uni-badge>
			</view>
		</MySteps>
		<view v-if="!dutys.length">
			<view class="null_duty_data">
				没有值日的
			</view>
			<MyNull img="nullDuty.png" />
		</view>
		<uni-fab 
			v-if="isAdmin"
			ref="fabRef" 
			:pattern="pattern" 
			:content="content"
			horizontal="right" 
			vertical="bottom"
			@trigger="clickAdminAddFun"
			direction="vertical"/>
		<view v-else class="add_duty" @click="openEditDuty">
			<MyIcons size="130rpx" :src="joinSystemPath('addNotice.png')" />
		</view>
		<view class="footer_btn" v-if="isHaveFillDuty">
			<MyButton fontSize="28rpx" :borderColor="primary_hot_color" padding="0rpx" :bgc="primary_hot_color" :clickFun="isDeleteAllFillDutyFun">删除所有轮流值日</MyButton>
			<MyButton fontSize="28rpx" padding="0rpx" :bgc="primary_light_color" :clickFun="isAutoRefreshDutyFun">重新刷新轮流值日</MyButton>
		</view>
		<MyModal :openModalFlag="modalIsEditDutyFlag" :okFun="submitDutyFun">
			<template #title>
				{{modalType}}我的{{formData.weekType=== WeekType.SIGLE ? '【单周】' : '【双周】'}}值日
			</template>
			<template #content>
				<EditorDuty :formData="editDutyFormData" @changeEditDutyDataEmit="changeEditDutyDataFun" />
			</template>
		</MyModal>
		<MyModal :openModalFlag="modalIsDeleteDutyFlag" :okFun="submitDeleteDutyFun" key="modalIsDeleteDutyFlag">
			<template #title>
				确定删除我的值日吗
			</template>
		</MyModal>
		<MyModal :openModalFlag="modalIdDeleteAllFillDutyFlag" :okFun="deleteAllFillDutyFun" key="modalIdDeleteAllFillDutyFlag">
			<template #title>
				确认删除所有{{formData.weekType === WeekType.SIGLE ? '单周' : '双周'}}轮流值日吗？
			</template>
			<template #content>
				<view class="modal_info">该操作只会删除{{formData.weekType === WeekType.SIGLE ? '单周' : '双周'}}的轮流值日的人员[粉]，删除后，将只剩正常值日.</view>
			</template>
		</MyModal>
		<MyModal :openModalFlag="modalIdAutoRefreshDutyFlag" :okFun="autoRefreshDutyFun" key="modalIdAutoRefreshDutyFlag">
			<template #title>
				确认重新刷新{{formData.weekType === WeekType.SIGLE ? '单周' : '双周'}}轮流值日列表？
			</template>
			<template #content>
				<TipInfo :color="shallow_text_color" id="16"></TipInfo>
			</template>
		</MyModal>
		<MyModal :openModalFlag="modalGoClockFlag"  :cancelFun="cancelGoClockPage" :okFun="goClockPage" key="modalGoClockFlag">
			<template #title>
				<view style="text-align: center;">
					今天轮到您值日
				</view>
				<view style="text-align: center;">
					去打卡啦
				</view>
			</template>
			<template #content>
				<MyNull img="goClock2.png"></MyNull>
			</template>
		</MyModal>
	</view>
</template>

<script setup>
	import {
		onShow,
		onLoad,
		onHide
	} from '@dcloudio/uni-app'
	import {
		ref,
		computed,
		nextTick,
		onUnmounted
	} from 'vue'

	import MySteps from '@/components/MySteps/MySteps.vue'
	import DutyCard from '@/components/Dormitory/DutyCard/DutyCard.vue'
	import EditorDuty from '@/components/Dormitory/EditorDuty/EditorDuty.vue'
	import Tips from '@/components/Tips/Tips.vue'
	import MyNull from '@/components/MyNull/MyNull.vue'
	import ClockNoN from '@/components/Dormitory/ClockNoN/ClockNoN.vue'
	import MyIcons from '@/components/MyIcons/MyIcons.vue'
	import MyModal from '@/components/MyModal/MyModal.vue'
	import AdBanner from '@/components/AdBanner/AdBanner.vue'
	import TipInfo from '@/components/TipInfo/TipInfo.vue'

	import {
		dynamicStyleStore
	} from '@/stores/dynamicStyle.js'
	import {
		userStore
	} from '@/stores/user'

	import {
		DormitoryModel
	} from '@/service/model/dormitory.js'

	import {
		deleteStrByPatten,
		getNowWeek
	} from '@/utils/changeData.js'
	import {
		openMessageAuth
	} from '@/utils/messageAuth.js'
	import {
		joinSystemPath
	} from '@/utils/imgJoinName.js'

	import {
		verifyIsLogin,
		verifyFormData,
		MessageAndBindPhone
	} from '@/hooks/verify.js'
	import MyItemVue from '../../../components/MyItem/MyItem.vue'
	import moment from 'moment'
	
	import { 
		DefaultPhone,
		DutyAddType,
		IsPauseDuty,
		WeekType
	} from '../../../enum/GlobalEnum'

	const user_store = userStore()

	const dynamicStyle_store = dynamicStyleStore()
	const dormitoryModel = new DormitoryModel()
	
	const fabRef = ref(null)

	const {
		primary_hot_color,
		primary_light_color,
		shallow_text_color,
		primary_main_bgc,
		primary_text_color
	} = dynamicStyle_store.dormitoryStyle
	
	const pattern = ref({
			color: primary_text_color,
			backgroundColor: '#fff',
			buttonColor: primary_hot_color,
		})
	const content = ref([{
			iconPath: '../../../../static/iconpng/orther/addUsersDuty.png',
			selectedIconPath: '../../../../static/iconpng/orther/addUsersDuty.png',
			text: '安排室友',
			active: false
		},
		{
			iconPath: '../../../../static/iconpng/orther/addMineDuty.png',
			selectedIconPath: '../../../../static/iconpng/orther/addMineDuty.png',
			text: '添加自己',
			active: false
		}
	])

	const formData = ref({
		limit: 1000,
		page: 0,
		orderBy: 'time.desc',
		week: '8',
		time: '99:99',
		weekType:0
	})
	const nowDormitoryWeekType = ref(0)

	const dormitoryId = ref(uni.getStorageSync('homeData').dormitory_id)
	
	const clocks=ref(false)
	const isHaveFillDuty = ref(false)
	
	const noBindPhone = computed(()=>user_store.userInfo.phone === DefaultPhone)
	const isAdmin = computed(()=>user_store.userInfo.user_id === dormiotryAdmin.value)

	const init = () => {
		dutys.value = []
	}

	const dutys = ref([])
	const nowWeek = ref(0)
	const clockDuty=ref(null)
	const timerRef = ref(null)
	const dormiotryAdmin = ref('')
	const items = ref(['单周','双周'])
	const dormitoryDutyIsPause = ref(false)
	
	const clickAdminAddFun = (e)=>{
		const {index} = e
		switch(index){
			case 0:
				uni.navigateTo({
					url:'/pages/Dormitory/DutyAdmin/DutyAdmin?chooseWeekType='+formData.value.weekType+'&nowDormitoryWeekType='+nowDormitoryWeekType.value
				})
				break
			case 1:
				openEditDuty()
				break
		}
		fabRef.value?.close()
	}
	//步骤条颜色
	const stepColor = (item) => {
		let color = ''
		if (item.week > nowWeek.value) {
			color = shallow_text_color
		} else if (item.week < nowWeek.value) {
			color = primary_light_color
		} else {
			color = primary_hot_color
		}
		return color
	}
	
	const cancelGoClockPage=()=>{
		modalGoClockFlag.value = -Math.random()
		MessageAndBindPhone()
		// noBindPhone.value && uni.$emit('openPhonePopubFlag',()=>{},false)
	}
	
	const goClockPage=()=>{
		uni.navigateTo({
			url:`/pages/Dormitory/DutyClock/DutyClock?dutyId=${clockDuty.value.id}`
		})
		modalGoClockFlag.value = -Math.random()
	}
	
	//排行
	const getEveryDutyClockCountFun=async()=>{
		const {data,success} = await dormitoryModel.getEveryDutyClockCount({},dormitoryId.value)
		if(success){
			clocks.value = data
			dormiotryAdmin.value = data[0].dormitory.admin_user_id
		}
	}
	
	const verifyShowAutoRefreshBtnFun=(data)=>{
		for(let i=0;i<data.length;i++){
			const dutysItem=data[i].duty
			for(let j=0;j<dutysItem.length;j++){
				const {addType} = dutysItem[j]
				if(addType === DutyAddType.NO_SELF_ADD){
					nextTick(()=>{
						isHaveFillDuty.value = true
					})
				}
			}
		}
	}
	
	const getDutys = async (isTimer=false) => {
		if(!isTimer){
			isHaveFillDuty.value = false
		}
		const {
			data,
			success
		} = await dormitoryModel.getDutys(formData.value, dormitoryId.value)
		if (success) {
			data.forEach(item => {
				item.duty[0].time = deleteStrByPatten(item.duty[0].time, /:\d{2}.\d{6}/)
			})
			dutys.value = data
			nowWeek.value = getNowWeek()
			if(!isTimer){
				verifyShowAutoRefreshBtnFun(data)
			}
			for(let i=0;i<data.length;i++){
				const dutysItem=data[i].duty
				for(let j=0;j<dutysItem.length;j++){
					const {user_id,week,clocked,createAt,dutyWeekType} = dutysItem[j]
					const timeFormat = "YYYY-MM-DD"
					const nextDay = moment().add(1,'days').format(timeFormat)
					const dutyCreate = moment(createAt).format(timeFormat)
					if(nextDay===dutyCreate){
						return
					}
					if(
						user_id === user_store.userInfo.id &&
						week === (moment().weekday() || 7) &&
						clocked !== moment().format('YYYY-MM-DD')&&
						dutyWeekType===nowDormitoryWeekType.value
					){
						clockDuty.value = dutysItem[j]
						//只有用户在了解过订阅新手引导后，才能弹出轮到打卡了
						if(uni.getStorageSync('tipUserAlwayMessage1') && !isTimer && !dormitoryDutyIsPause.value){
							modalGoClockFlag.value = Math.random()
						}
						return
					}
				}
			}
			dutys.value = data
		}
	}

	const modalType = ref('添加')
	//添加修改值日
	const modalIsEditDutyFlag = ref(0)
	const modalIsDeleteDutyFlag = ref(0)
	const modalGoClockFlag=ref(0)
	const modalIdAutoRefreshDutyFlag = ref(0)
	const modalIdDeleteAllFillDutyFlag=ref(0)
	const editDutyFormData = ref({
		time: '09:00',
		week: 1
	})
	const editDutyFormDataSchema = {
		time: {
			required: true,
			tip: '时间'
		}
	}
	const changeEditDutyDataFun = (e) => {
		const dateData = {
			...e,
			week: parseInt(e.week) + 1
		}
		editDutyFormData.value = dateData
	}
	//添加值日
	const openEditDuty = () => {
		editDutyFormData.value = {
			time: '09:00',
			week: 1
		}
		modalType.value = '添加'
		modalIsEditDutyFlag.value = Math.random()
	}

	//提交添加修改值日
	const submitDutyFun = async () => {
		verifyFormData(editDutyFormData.value, editDutyFormDataSchema)
		const {
			data,
			success
		} = modalType.value === '添加' ?
			await dormitoryModel.postAddDuty({
				...editDutyFormData.value,
				dutyWeekType:formData.value.weekType
			}, dormitoryId.value) :
			await dormitoryModel.patchDuty({
				...editDutyFormData.value,
				dutyWeekType:editDutyData.value.dutyWeekType
			}, editDutyData.value.id)

		if (success) {
			uni.$emit('tips', data, 'success')
			init()
			setTimeout(()=>{
				getDutys()
			},300)
			MessageAndBindPhone()	
		}
	}
	
	const onChooseFun=(e)=>{
		formData.value.weekType = e.currentIndex
		dutys.value=[]
		getDutys()
	}
	
	//是否重新刷新轮流值日
	const isAutoRefreshDutyFun = ()=>{
		modalIdAutoRefreshDutyFlag.value = Math.random()
	}
	const autoRefreshDutyFun=async()=>{
		const {data,success} = await dormitoryModel.postAutoRefreshDuty({dutyWeekType:formData.value.weekType},dormitoryId.value)
		if(success){
			uni.$emit('tips',data,'success',2000)
			getDutys()
		}
	}
	
	//是否删除所有轮流值日
	const isDeleteAllFillDutyFun=()=>{
		modalIdDeleteAllFillDutyFlag.value = Math.random()
	}
	const deleteAllFillDutyFun=async()=>{
		const {data,success} = await dormitoryModel.deleteAllFillDuty({dutyWeekType:formData.value.weekType},dormitoryId.value)
		if(success){
			uni.$emit('tips',data,'success',2000)
			getDutys()
		}
	}

	//验证是否操作的自己的值日
	const verifyIsMyDuty = (item) => {
		if (item.user_id !== user_store.userInfo.id) {
			const tip = '请不要操作别人的值日'
			uni.$emit('tips', tip, 'warn')
			throw new Error(tip)
		}
	}

	//编辑我的值日
	const editDutyData = ref({})
	const openEditDutyModalFun = (item) => {
		verifyIsMyDuty(item)
		const data = {
			...item
		}
		modalType.value = '编辑'
		modalIsEditDutyFlag.value = Math.random()
		editDutyData.value = item
		editDutyFormData.value = {
			week: data.week,
			time: deleteStrByPatten(data.time, /:\d{2}.\d{6}/)
		}
	}

	const submitDeleteDutyFun = async () => {
		const {
			data,
			success
		} = await dormitoryModel.deleteDuty({}, editDutyData.value.id)
		if (success) {
			uni.$emit('tips', data, 'success')
			init()
			setTimeout(()=>{
				getDutys()
			},300)
		}
	}
	//是否删除值日
	const isDeleteDutyModelFun = (item) => {
		verifyIsMyDuty(item)
		editDutyData.value = item
		modalIsDeleteDutyFlag.value = Math.random()
	}

	onShow(() => {
		getDutys()
		getEveryDutyClockCountFun()
		timerRef.value = setInterval(()=>{
			getDutys(true)
		},2000)
	})
	onUnmounted(()=>{
		clearInterval(timerRef.value)
	})
	
	onHide(()=>{
		clearInterval(timerRef.value)
	})
	
	onLoad((opt)=>{
		const {dormitory_id,isPauseDuty,dormitoryWeekType}=opt
		if(Number(isPauseDuty) === IsPauseDuty.YES){
			dormitoryDutyIsPause.value = true
			nextTick(()=>uni.$emit('tips','当前宿舍值日是暂停状态,请前往--宿舍设置关闭它','info',4000))
		}
		formData.value.weekType = Number(dormitoryWeekType)
		nowDormitoryWeekType.value = Number(dormitoryWeekType)
		if(dormitory_id){
			dormitoryId.value=dormitory_id
		}
	})
</script>

<style lang="less">
	.modal_info{
		color: v-bind(primary_text_color);
		font-size: 28rpx;
	}
	.dutys_box {
		// width: 100%;
		min-height: calc(120vh);
		padding: 20rpx;
		background-color: v-bind(primary_main_bgc);
		.choose{
			padding-top: 20rpx;
			background-color: v-bind(primary_main_bgc);
			z-index: 2;
		}
		.uni-badge--x {
			display: block !important;
			position: relative;
		}
		.null_duty_data {
			display: flex;
			justify-content: center;
			color: v-bind(primary_hot_color);
		}

		.add_duty {
			width: 130rpx;
			height: 130rpx;
			position: fixed;
			bottom: 100rpx;
			right: 50rpx;
			z-index: 10;
			background-color: v-bind(primary_hot_color);
			border-radius: 100rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
	.footer_btn{
		margin-bottom: 20rpx;
		display: grid;
		grid-template-columns: 1fr 1fr;
		column-gap: 20rpx;
	}
</style>
